package com.wffz.task;

import com.wffz.comm.utils.DateUtils;
import com.wffz.po.Patch;
import com.wffz.service.PatchService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.SQLOutput;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author sunlei
 * @className ScheduleOneTask
 * @Description
 * @date 2023-02-12 10:52
 **/
@Data
@Slf4j
@Component
@PropertySource("classpath:/task-config.ini")
@EnableScheduling
public class ScheduleOneTask implements SchedulingConfigurer {

    @Value("${one.cron}")
    private String cron;


    @Resource
    private PatchService patchService;


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> process(),
                triggerContext -> {
                    if (cron.isEmpty()) {
                        System.out.println("cron is null");
                    }
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                });
    }

    private void process() {
        log.info("每天凌晨0点执行，插入每期数据，执行时间:" + DateUtils.getNowDate());
        String v = stringRedisTemplate.opsForValue().get("task_data");
        if (v.equals("0")) {
            log.info("业务定时任务未开启");
            return;
        }
        String patchs[] = {"0", "1", "2", "3"};
        for (String type : patchs) {
            // 获取当天数据  如果没有  新增当天数据
            String nowDay = DateUtils.dateTimeNow("yyyyMMdd");
            int nowDayCount = patchService.getPatchCountByDay(nowDay, type);
            if (nowDayCount <= 0) {
                patchService.saveDayPatch(nowDay, type);
            }
            // 获取第二天数据  如果没有  新增
            String nextDay = DateUtils.getNextDayYyyyMmDd();
            int nextDayCount = patchService.getPatchCountByDay(nextDay, type);
            if (nextDayCount <= 0) {
                patchService.saveDayPatch(nextDay, type);
            }
        }

    }


}
